#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#include "interface_capture.h"

//************************************************************************
//                         contador_files
//
// Nota: Para resetear el contador borrar el fichero.
//************************************************************************
int contador_files (const char *file, int next)
{
  int n;
  FILE *f = fopen(file, "r+");
  if (f == NULL)
  {
    //No existe el archivo
    f = fopen(file, "w");
    if (f == NULL)
    {
      fprintf(stderr, "Error: contador_files: No se puede abrir el archivo %s.\n",file);
      fflush(stderr);
      return -1;
    }
    n=1;
  }
  else
  {
    int nread = fscanf(f, "%d", &n);
    if (nread != 1)
      n=1;
  }
  if (next >= 0)
      n= next;
 
  rewind(f);
  fprintf(f, "%3d ", n+1);
  fclose(f);
  return n;
}

//************************************************************************
//                         name_file
//
// Esta función devuelve el nombre del video que se quiere grabar.
// El formato del nombre es:
//    - Índice (num)
//    - Hora (hh-mm-ss)
//    - Día (dd-mm-aa)
//************************************************************************

char* get_name_file_by_date (char * file_name, const char * Next_Video_File, int next)
{
  time_t timer;
  struct tm *p_tm;

  time (&timer);
  p_tm = localtime (&timer);

  if (next <0 )
      next = contador_files(Next_Video_File, -1);
  
  sprintf(file_name, "_%02d_%02d-%02d-%02d_%02d-%02d", 
	  next,
	  1900 + p_tm->tm_year,
	  1 + p_tm->tm_mon,
	  p_tm->tm_mday,
	  p_tm->tm_hour,
	  p_tm->tm_min);

  return file_name;
}




float difftime_ms(struct timeval t2, struct timeval t1)
{
    return (float)(t2.tv_sec - t1.tv_sec)*1.0e3 + (float)(t2.tv_usec - t1.tv_usec)/1.0e3;
}


int ntrace1[100];
int ntrace2[100];
void TRACE(int a, const char * data)
{
    if (data)
	printf("\n-------------(%d)-TRACE %d---%s----\n", a, ntrace1[a]++, data);
    else
	printf("\n-------------(%d)-TRACE %d----------\n", a, ntrace2[a]++);
}


void Rectangle2(IplImage * image, CvRect rect, CvScalar color, int thckness)
{
    cvRectangle(image, cvPoint(rect.x, rect.y), cvPoint(rect.x + rect.width, rect.y + rect.height), color, thckness);
}

